<template>
  <div class="login-container">
    <el-row>
      <div>
        <div style="color: transparent">占位符</div>
      </div>
      <div style="width: 100%">
        <el-form
          ref="formRef"
          class="login-form"
          label-position="center"
          :model="form"
          :rules="rules"
        >
          <!-- <div class="title">Dispatch</div> -->
          <!-- <div class="title-tips"> -->
          <!-- <img
              src="@/assets/logo.png"
              style="border-radius: 100%; height: 40px; width: 40px"
            />
            &nbsp;
            {{ title }} -->

          <!-- </div> -->
          <div class="title-tips-2">
            <div class="t-t-2-1">
              <div>科尔沁史诗音像档案系统</div>
              <!-- <div>平台单位客户端</div> -->
            </div>
            <!-- <div class="t-t-2-2">
              <div>（试运行）</div>
            </div> -->
          </div>
          <!-- <div class="login-navs">
            <div
              :class="page == 1 ? 'login-nav-item' : 'login-nav-item-on'"
              style="cursor: not-allowed"
              @click="page = 2"
            >
              用户登录
            </div>
            <div
              :class="page == 2 ? 'login-nav-item' : 'login-nav-item-on'"
              @click="page = 2"
            >
              单位登录
            </div>
            <div
              :class="page == 3 ? 'login-nav-item' : 'login-nav-item-on'"
              style="cursor: not-allowed"
              @click="page = 2"
            >
              CA登录
            </div>
          </div> -->
          <template v-if="page == 2">
            <el-form-item prop="username" style="margin-top: 30px">
              <el-input
                v-model.trim="form.username"
                v-focus
                :disabled="loading"
                :placeholder="translateTitle('请输入用户名')"
                tabindex="1"
                type="text"
              >
                <template #prefix>
                  <vab-icon icon="user-line" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="passwordRef"
                v-model.trim="form.password"
                :disabled="loading"
                :placeholder="translateTitle('请输入密码')"
                tabindex="2"
                :type="passwordType"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <vab-icon icon="lock-line" />
                </template>
                <template v-if="passwordType === 'password'" #suffix>
                  <vab-icon
                    class="show-password"
                    icon="eye-off-line"
                    @click="handlePassword"
                  />
                </template>
                <template v-else #suffix>
                  <vab-icon
                    class="show-password"
                    icon="eye-line"
                    @click="handlePassword"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-input
                v-model.trim="form.verificationCode"
                :disabled="loading"
                :placeholder="translateTitle('验证码') + previewText"
                tabindex="3"
                type="text"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <vab-icon icon="barcode-box-line" />
                </template>
              </el-input>
              <el-image class="code" :src="base64" @click="changeCode" />
            </el-form-item>
            <el-button
              class="login-btn"
              :loading="loading"
              style="font-size: 14px"
              type="primary"
              @click="handleLogin"
            >
              {{ translateTitle('登录') }}
            </el-button>
          </template>
          <template v-if="page == 3">
            <el-form-item prop="username" style="margin-top: 30px">
              <el-input
                v-model.trim="form.username"
                v-focus
                :placeholder="translateTitle('请输入用户名')"
                tabindex="1"
                type="text"
              >
                <template #prefix>
                  <vab-icon icon="user-line" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="passwordRef"
                v-model.trim="form.password"
                :placeholder="translateTitle('请输入CA密码')"
                tabindex="2"
                :type="passwordType"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <vab-icon icon="lock-line" />
                </template>
                <template v-if="passwordType === 'password'" #suffix>
                  <vab-icon
                    class="show-password"
                    icon="eye-off-line"
                    @click="handlePassword"
                  />
                </template>
                <template v-else #suffix>
                  <vab-icon
                    class="show-password"
                    icon="eye-line"
                    @click="handlePassword"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-input
                v-model.trim="form.verificationCode"
                :placeholder="translateTitle('验证码') + previewText"
                tabindex="3"
                type="text"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <vab-icon icon="barcode-box-line" />
                </template>
              </el-input>
              <el-image class="code" :src="base64" @click="changeCode" />
            </el-form-item>
            <el-button
              class="login-btn"
              :disabled="true"
              :loading="loading"
              style="
                background-color: #58b5e1;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="handleLogin"
            >
              {{ translateTitle('敬请期待') }}
            </el-button>
            <router-link :disabled="true" to="/login">
              <div style="margin-top: 20px; color: #f6f4fc">
                {{ translateTitle('下载CA驱动') }}
              </div>
            </router-link>
          </template>
          <template v-if="page == 1">
            <el-form-item prop="username" style="margin-top: 30px">
              <el-input
                v-model.trim="form.username"
                v-focus
                :placeholder="translateTitle('请输入用户名')"
                tabindex="1"
                type="text"
              >
                <template #prefix>
                  <vab-icon icon="user-line" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="passwordRef"
                v-model.trim="form.password"
                :placeholder="translateTitle('请输入密码')"
                tabindex="2"
                :type="passwordType"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <vab-icon icon="lock-line" />
                </template>
                <template v-if="passwordType === 'password'" #suffix>
                  <vab-icon
                    class="show-password"
                    icon="eye-off-line"
                    @click="handlePassword"
                  />
                </template>
                <template v-else #suffix>
                  <vab-icon
                    class="show-password"
                    icon="eye-line"
                    @click="handlePassword"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-input
                v-model.trim="form.verificationCode"
                :placeholder="translateTitle('验证码') + previewText"
                tabindex="3"
                type="text"
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <vab-icon icon="barcode-box-line" />
                </template>
              </el-input>
              <el-image class="code" :src="base64" @click="changeCode" />
            </el-form-item>
            <el-button
              class="login-btn"
              :loading="loading"
              style="
                background-color: #58b5e1;
                color: #fff;
                border: 0px;
                font-size: 14px;
              "
              @click="handleLogin"
            >
              {{ translateTitle('登录') }}
            </el-button>
            <!-- <router-link to="/register">
              <div style="margin-top: 20px; color: #f6f4fc">
                {{ translateTitle('注册') }}
              </div>
            </router-link> -->
          </template>
        </el-form>
      </div>
      <!-- <el-col :lg="1" :md="1" :sm="24" :xl="1" :xs="24">
        <div style="color: transparent">占位符</div>
      </el-col> -->
    </el-row>
  </div>
</template>

<script>
  import {
    computed,
    defineComponent,
    nextTick,
    onBeforeMount,
    getCurrentInstance,
    onMounted,
    reactive,
    toRefs,
    watchEffect,
  } from 'vue'
  import { useStore } from 'vuex'
  import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
  import { translateTitle } from '@/utils/i18n'
  import { isPassword } from '@/utils/validate'
  import { getVertifyCode } from '@/api/public'
  import { baseURL } from '@/config'

  export default defineComponent({
    name: 'Login',
    directives: {
      focus: {
        inserted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    setup() {
      const store = useStore()
      const route = useRoute()
      const router = useRouter()
      const { proxy } = getCurrentInstance()

      const login = (form) => store.dispatch('user/login', form)

      const validateUsername = (rule, value, callback) => {
        if ('' === value) callback(new Error(translateTitle('用户名不能为空')))
        else callback()
      }
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value))
          callback(new Error(translateTitle('密码不能少于6位')))
        else callback()
      }

      const state = reactive({
        formRef: null,
        form: {
          username: '',
          password: '',
          verificationCode: '',
        },
        page: 2,
        code: 2,
        verifyCode: null,
        rules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              validator: validateUsername,
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
          verificationCode: [
            {
              required: true,
              trigger: 'blur',
              message: '验证码不能空',
            },
          ],
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        timer: 0,
        base64: '',
        previewText: '',
      })

      const handleRoute = () => {
        // return state.redirect === '/404' || state.redirect === '/403'
        //   ? '/'
        //   : state.redirect
        //跳到首页
        return '/index'
      }
      const handlePassword = () => {
        state.passwordType === 'password'
          ? (state.passwordType = '')
          : (state.passwordType = 'password')
        nextTick(() => {
          state['passwordRef'].focus()
        })
      }
      const handleLogin = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (
              state.form.verificationCode.toLowerCase() !=
              state.verifyCode.toLowerCase()
            ) {
              proxy.$baseMessage('验证码错误', 'error')
              changeCode()
              return false
            }
            try {
              state.loading = true
              await login(state.form).catch(() => {})
              await router.push(handleRoute())
            } finally {
              state.form.verificationCode = null
              state.verifyCode = null
              state.loading = false
            }
          }
        })
      }
      const changeCode = async () => {
        const {
          data: { code, base64 },
        } = await getVertifyCode()
        state.verifyCode = code
        state.base64 = base64
        //如果是本地调试，就自动填充验证码
        if (baseURL.includes('localhost')) {
          state.form.verificationCode = state.verifyCode
          state.form.username = 'dev'
          state.form.password = 'dqh512341'
        }
      }

      onBeforeMount(() => {
        // state.form.username = 'admin'
        // state.form.password = '123456'
        // 为了演示效果，会在官网演示页自动登录到首页，正式开发可删除
        if (
          document.domain === 'vue-admin-beautiful.com' ||
          document.domain === 'chu1204505056.gitee.io'
        ) {
          state.previewText = '（演示地址验证码可不填）'
          state.timer = setTimeout(() => {
            handleLogin()
          }, 0)
        }
      })

      onMounted(() => {
        changeCode()
      })

      watchEffect(() => {
        state.redirect = (route.query && route.query.redirect) || '/'
      })

      onBeforeRouteLeave((to, from, next) => {
        clearInterval(state.timer)
        next()
      })

      return {
        translateTitle,
        ...toRefs(state),
        title: computed(() => store.getters['settings/title']),
        handlePassword,
        handleLogin,
        changeCode,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .login-container {
    height: 100vh;
    background: url('~@/assets/login_images/background.jpg') center center fixed
      no-repeat;
    background-size: cover;
  }

  .login-form {
    position: relative;
    width: 700px;
    min-height: 50vh;
    padding: 4.5vh;
    margin: calc((100vh - 475px) / 2) 5vw 5vw;
    margin-left: calc((100% - 660px) / 2);
    overflow: hidden;
    background: url('~@/assets/login_images/login_form.png');
    background-size: 100% 100%;
    background-color: rgba(20, 193, 249, 0.4);
    border-radius: 12px;

    .title {
      font-size: 54px;
      font-weight: 500;
      color: var(--el-color-white);
    }

    .title-tips {
      justify-content: center;
      margin-top: 20px;
      margin-bottom: 30px;
      font-size: 26px;
      font-weight: 400;
      display: flex;
      flex-direction: row;
      align-items: center;
      color: var(--el-color-white);
    }

    .title-tips-2 {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      color: var(--el-color-white);
      font-size: 28px;
      font-weight: 400;
      margin-top: 20px;
      margin-bottom: 30px;
      // .t-t-2-1 {
      //   div:nth-child(2) {
      //     color: #cfd3dc;
      //     font-weight: bold;
      //   }
      // }
      .t-t-2-2 {
        font-size: 30px;
      }
    }

    .login-btn {
      display: inherit;
      width: 100%;
      height: 50px;
      margin-top: 5px;
      border: 0;

      &:hover {
        opacity: 0.9;
      }

      .forget-passwordword {
        width: 100%;
        margin-top: 40px;
        text-align: left;

        .forget-password {
          width: 129px;
          height: 19px;
          font-size: 20px;
          font-weight: 400;
          color: rgb(58, 70, 235);
        }
      }
    }

    .tips {
      margin-bottom: 10px;
      font-size: $base-font-size-default;
      color: var(--el-color-white);

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .title-container {
      position: relative;

      .title {
        margin: 0 auto 40px auto;
        font-size: 34px;
        font-weight: bold;
        color: var(--el-color-primary);
        text-align: center;
      }
    }

    i {
      position: absolute;
      top: 8px;
      left: 5px;
      z-index: $base-z-index;
      font-size: 14px;
      color: #d7dee3;
      cursor: pointer;
      user-select: none;
    }

    .show-password {
      position: absolute;
      right: 25px;
      left: -35px;
      font-size: 14px;
      color: #d7dee3;
      cursor: pointer;
      user-select: none;
    }

    :deep() {
      .el-form-item {
        padding-right: 0;
        margin: 20px 0;
        color: #454545;
        background: transparent;
        border: 1px solid transparent;
        border-radius: 2px;

        &__content {
          min-height: $base-input-height;
          line-height: $base-input-height;
        }

        &__error {
          position: absolute;
          top: 100%;
          left: 18px;
          font-size: $base-font-size-small;
          line-height: 18px;
          color: var(--el-color-error);
        }
      }

      .el-input {
        box-sizing: border-box;

        input {
          height: 48px;
          padding-left: 35px;
          font-size: $base-font-size-default;
          line-height: 58px;
          background: #f6f4fc;
          border: 0;
        }
      }

      .code {
        position: absolute;
        top: 4px;
        right: 4px;
        cursor: pointer;
        border-radius: $base-border-radius;
        width: 120px;
        height: 40px;
      }
    }
    .login-navs {
      width: 100%;
      display: flex;
      flex-direction: row;
      height: 40px;
      margin-top: 10px;
      align-items: flex-end;
      div {
        flex: 10;
        font-size: 18px;
        cursor: pointer;
        text-align: center;
        padding-bottom: 6px;
        border-bottom: 2px solid #aaaaaa;
      }
      div:nth-child(1) {
        // text-align: left;
        flex: 10;
      }
      div:nth-child(3) {
        flex: 10;
        // text-align: right;
      }
      .login-nav-item {
        color: #75baff;
        // transform: scale(1.2);
        border-color: #75baff;
      }
      .login-nav-item-on {
        color: hsl(0, 0%, 85%);
      }
    }
  }
</style>
